// ajax.js
import ajax,{Fetcher} from '@/uni_modules/u-ajax'
import tips from "@/utils/tips";
import {useUserInfoStore} from "@/store/modules/user";
import type {HttpRequestConfig, HttpResponse} from "@/types/global";
const {token,isLogin} = storeToRefs(useUserInfoStore())
const isLoading = ref<boolean>(false)

// 创建请求实例    初始配置
const instance = ajax.create({
    baseURL: import.meta.env.VITE_API__BASE_PATH
})

// 当前请求的fetcher用于取消请求
export const fetcher = ref(null)

// 添加请求拦截器
instance.interceptors.request.use(
    (config:HttpRequestConfig) => {
        fetcher.value = config.fetcher
        if (config.isLoading && !isLoading.value) {
            isLoading.value = true
            tips.showLoading()
        }

        config.header.Token = isLogin.value && token.value
        return config
    },
    error => {
        // 对请求错误做些什么
        return Promise.reject(error)
    }
)

// 添加响应拦截器
instance.interceptors.response.use(
    (response) => {
        let config = response.config as HttpRequestConfig
        if (config.isLoading) {
            isLoading.value = false
            tips.hideLoading()
        }
        if (config.isMessage) tips.showToast(response.data.msg)
        // 对响应数据做些什么
        return response
    },
    error => {
        // 对响应错误做些什么
        return Promise.reject(error)
    }
)

export const $get=<T> (url: string, data: Record<string, any> = {},option?: HttpRequestConfig) => {
    return instance.get<HttpResponse<T>>(url, data, {...option, fetcher: new Fetcher()})
}

export const $post=<T> (url: string, data: Record<string, any> = {},option?: HttpRequestConfig) => {
    return instance.post<HttpResponse<T>>(url, data, {...option, fetcher: new Fetcher()})
}

export default instance
